package com.xls.commonlibrary.ui.dialog;

import android.app.Dialog;
import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.xls.commonlibrary.R;

import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Action;
import io.reactivex.rxjava3.functions.Consumer;

public class TimerDialog extends Dialog {

    AppCompatActivity context;
    Disposable countdownDisposable;
    // 倒计时  秒
    private int time = 15;

    TextView tv_timer;

    public static TimerDialog newInstance(AppCompatActivity context) {
        return new TimerDialog(context);
    }

    private TimerDialog(AppCompatActivity context) {
        super(context, R.style.TransparentDialog);
        this.context = context;
    }

    @Override
    public void show() {
        super.show();


        startTimer();
    }

    @Override
    public void dismiss() {
        super.dismiss();

        if (countdownDisposable != null) {
            countdownDisposable.dispose();
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCancelable(false);
        setCanceledOnTouchOutside(false);
        getWindow().setContentView(R.layout.dialog_ad_timer);
        initView();
    }

    private void initView() {
        tv_timer = findViewById(R.id.tv_timer);


    }

    void startTimer() {
        //intervalRange四个参数分别为：从0开始、到60结束、延时0开始，
        // 单位时间（NANOSECONDS,MICROSECONDS,MILLISECONDS,SECONDS,MINUTES,HOURS,DAYS）。
        countdownDisposable
                = Flowable.intervalRange(0, time, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        tv_timer.setText((time - aLong) + "");
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        dismiss();
                    }
                })
                .doOnError(new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Throwable {
                        dismiss();
                    }
                })
                .subscribe();

    }
}
